Repository navigation
fix(collab,sync): journal-fenced CRDT, multi-hunk diff3, and 8-peer exit safety - #355
Conversation
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 시각적 편집에서 같은 요소의 충돌이 발생하면 동료의 다른 변경까지 조용히 삭제할 수 있습니다.
- 새 HTTP 동기화 경로의 쓰기 권한 검사와 조건부 업로드의 JSON 유효성 검사를 확인했습니다. 이전 리뷰 차단 항목은 없습니다.
- 클린 체크아웃에 패키지 도구와 의존성이 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| (live − orig) and ours (html − orig), merged three ways; where they | ||
| collide on the same words the patch wins, as it always did. */ | ||
| const merged = merge3(a.orig, live, msg.html); | ||
| const want = merged.ok ? merged.text : msg.html; |
There was a problem hiding this comment.
[P1] 같은 요소의 한 단어에서 충돌하면 merge3가 실패하고 msg.html 전체를 채택하므로, 해당 충돌과 무관한 동료의 다른 편집까지 diffSplices가 삭제하여 공유 문서에 전파합니다. 예를 들어 원문 cat sales, 동료 dog revenue, 내 패치 bird sales는 bird sales가 되어 revenue도 사라집니다. 실패 시 전체 요소로 덮어쓰지 말고 충돌을 보존·표시하거나 충돌한 부분만 별도 해결하면서 다른 변경은 유지해 주세요.
There was a problem hiding this comment.
Fixed in fc7362f. Added merge3PreferRight in src/lib/merge3.ts and wired both the stageDoc and live paths in VisualEdit.tsx to it so only the colliding token span takes msg.html while non-colliding peer edits in the same element (such as "cat sales" + "dog revenue" + "bird sales" -> "bird revenue") survive intact.
Verified with 36/36 node --test src/lib/sharedfile_restore.test.ts cases (including your cat sales / dog revenue / bird sales case, follow-up keystrokes, and multi-line HTML elements), 18/18 Playwright inline-edit.spec.ts and solo-handoff.spec.ts tests, and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 종료 시 충돌 응답을 처리하지 않아 staging/solo 편집 내용이 유실될 수 있습니다.
- 충돌 복사본 저장의 일시적 실패도 자동 재시도되지 않습니다.
- 이전 시각적 편집 차단 항목은 토큰 단위 우선 병합으로 수정된 것을 확인했으며, HTTP 동기화 경로의 쓰기 권한 검사도 확인했습니다.
- 클린 체크아웃에 패키지 도구와 의존성이 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true).catch(exitFailed(key)); | ||
| } else { | ||
| opts.soloApply!(e); | ||
| void syncCollab(syncURL, roomPayload(text), true).catch(exitFailed(key)); |
There was a problem hiding this comment.
[P1] staging에서 같은 단어를 동료가 먼저 수정한 뒤 이쪽이 유휴 저장 전에 탭을 닫으면 이 요청은 409를 받지만 catch는 전송 키만 초기화합니다. 페이지가 종료되면 버퍼와 함께 내 편집이 사라지고 충돌 복사본도 남지 않습니다. solo의 위 PUT에도 같은 문제가 있습니다. 종료 경로에서도 409 시 keepalive 충돌 복사본으로 보존하거나 종료 전에 내 버퍼의 내구성을 확보해 주세요.
There was a problem hiding this comment.
Fixed in 34193d0. Because a pagehide keepalive request can outlive the discarded page while its JS cannot run a second request on 409, flushExit now passes park_on_conflict: true on staging POST /ycollab/sync and X-Bdrive-Park-On-Conflict: 1 on solo PUT /upload/content so the hub allocates a collision-free If-None-Match: * conflict copy in that single request when the merge clashes. onExitError also keeps the client-side keepalive conflict-copy PUT as a fallback for older hubs and SPA unmounts.
Verified with 43/43 node --test src/lib/sharedfile_restore.test.ts cases and go test -race ./internal/webapp -run 'ParkOnConflict|TestUpload|TestYCollabSync' (including same-second multi-tab and two-process hub collision tests).
| // The same words changed two different ways: genuinely contended. | ||
| // Theirs is the file (it got there first); ours goes beside it. | ||
| if (landed) adopt(head.text, head.sha); | ||
| await preserve(cur, head.sha ?? ""); |
There was a problem hiding this comment.
[P1] solo 저장이 409로 거절되어 실제 충돌을 발견한 뒤 충돌 복사본 PUT이 일시적으로 503/네트워크 오류를 내면, preserve의 실패 결과를 버리고 중단합니다. 이미 유휴 타이머가 소진되어 사용자가 다시 입력하지 않으면 재시도가 없고, Done으로 나가면 유일한 버퍼가 사라질 수 있습니다. 실패 결과를 확인하여 기존 백오프로 같은 복사본을 재시도하고 보존되기 전에는 버퍼를 유지해 주세요.
There was a problem hiding this comment.
Fixed in 34193d0. Unified conflict parking across sendRoom, rebaseOnHead, and saveLoop MAX_REBASES into parkConflict, which sets stagingConflict = true, keeps the buffer unsaved when preserve fails, arms retryAfterFailure, and retries directly onto the same conflict-copy path in saveLoop (or parks keepalive on flushExit if the editor closes before the retry lands).
Verified with solo 409 clash: a park refused 503 is retried onto the same copy (both with and without close before retry) in src/lib/sharedfile_restore.test.ts (43/43 green) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 일반 저장 및 지연 접속의 충돌 복사본이 다른 탭의 복사본을 덮어써 편집 내용이 유실될 수 있습니다.
- 이전 시각적 편집의 무관한 변경 보존, 종료 요청의 서버 측 충돌 보관, 일시적 보관 실패 재시도 경로를 확인했습니다. 서버 측 종료 보관은 조건부 생성으로 이름 충돌을 처리하지만 클라이언트 측 보관은 그렇지 않습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| if (!oursToTheirs || oursToTheirs.from === oursToTheirs.to) { | ||
| saved = head.text; | ||
| rebase(head.sha); | ||
| await putText(contentURL(copy), text); // unconditional: a new path |
There was a problem hiding this comment.
[P1] 충돌 복사본 이름은 계정과 초 단위 시각으로 만들어지고 lastConflictMs는 탭마다 독립적이므로, 같은 사용자의 두 탭이 같은 파일의 충돌을 같은 초에 보관하면 동일한 경로를 무조건 PUT합니다. 나중 요청이 먼저 보관한 서로 다른 편집을 덮어쓰며 양쪽 모두 저장 성공으로 처리합니다. 기존 복사본이 있는 경우에도 동일합니다. 서버의 parkNewCopy처럼 If-None-Match: *로 원자적으로 생성하고 이름 충돌 시 새 이름으로 재시도하되, 응답 유실 후 동일 요청 재시도도 안전하게 처리해 주세요.
There was a problem hiding this comment.
Fixed in 88a19c4. preserve(), client exit conflict-copy writes (parkOnExit), and server room conflict-copy writes (parkCopy) now all send If-None-Match: *:
- When another tab already parked different bytes at that second (
409),preserve()mints the next whole-second path viamintConflictPath()and retries (andparkOnExitalso sendsX-Bdrive-Park-On-Conflict: 1so the hub steps+1sserver-side in one request onpagehide). - On a transient
503or lost response,preserve()keeps the same target path so the backoff retry hitsholdsBytes(200 unchanged) idempotently on both hub storage andDirSourcewithout creating a second copy.
Verified with 46/46 node --test src/lib/sharedfile_restore.test.ts cases, go test -race ./internal/webapp -run 'CreateOnly|ParkOnConflict|TestUpload|TestYCollabSync', and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- staging/solo 종료 시 빈 문서 변경이 전송되지 않아 마지막 삭제가 유실됩니다.
- 뒤로/앞으로 캐시 복원 후 종료 체크포인트를 기반 상태에 반영하지 않아 이미 보낸 편집이 중복 병합될 수 있습니다.
- 이전 충돌 복사본 덮어쓰기 차단 항목은 create-only 생성 및 이름 충돌 재시도 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| parkOnExit(copy, text, key); | ||
| return; | ||
| } | ||
| if (!text || text === saved) return; |
There was a problem hiding this comment.
[P1] 빈 문자열도 유효한 편집인데 !text에서 종료하면 staging/solo 문서를 전부 지운 직후 유휴 저장 전에 탭을 닫거나 편집 화면을 떠날 때 삭제가 전송되지 않습니다. 예를 들어 짧은 파일을 모두 지우고 바로 닫으면 기존 내용이 그대로 남습니다. text === saved만으로 변경 여부를 판정하고, 빈 내용도 일반 저장과 동일한 축소 확인 정책을 거쳐 종료 체크포인트로 보내 주세요.
There was a problem hiding this comment.
Fixed in 6a088a6. flushExit now checks text === saved && !roomNeedsFlush without skipping !text, so clearing a buffer to "" goes through the exit checkpoint and shrink-confirmation policy (askShrink on 422 when the page remains live), while blank conflict copies remain suppressed.
Verified with 55/55 node --test src/lib/sharedfile_restore.test.ts cases and ./check-dist.sh.
| opts.onConflictCopy?.(path); | ||
| }); | ||
| }; | ||
| const landed = (out: { parked?: string }) => { |
There was a problem hiding this comment.
[P1] pagehide 체크포인트 성공 시 저장된 텍스트/sha와 전송 이력을 갱신하지 않아 bfcache에서 복원된 staging 편집기가 이미 반영된 내용을 다시 옛 base에서 병합합니다. 예를 들어 log\n에서 x\n을 추가하고 pagehide 요청이 성공한 뒤 복원하여 x\n을 하나 더 추가하면 서버는 같은 위치에 x와 x,x를 독립 삽입으로 합쳐 세 줄을 저장합니다. 종료 요청도 일반 staging 체크포인트처럼 성공 시 응답을 적용하고, 응답이 불확실하거나 복원과 경합할 때는 전송 이력을 기록해 peek/prior_sent로 정산해 주세요.
There was a problem hiding this comment.
Fixed in 6a088a6. Staging flushExit now tracks the exit request in ambiguousRoomCheckpoint and exitSaving (awaited by both save() and join() if the page returns from bfcache while the request is still in flight), applies out.update, and updates saved/base on completion across staging and solo so post-pageshow edits build on the landed state or pass prior_sent/peek without duplicating lines.
Verified with 55/55 node --test src/lib/sharedfile_restore.test.ts cases (covering landed, 502, unsettled, and late-join() bfcache restoration) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 클라이언트 재병합이 서버의 JSON 유효성 검사를 우회하여 유효한 두 편집을 잘못된 JSON으로 저장할 수 있습니다.
- 이전 지적의 빈 버퍼 전송, bfcache 체크포인트 정산, 충돌 복사본 조건부 생성 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| const room = typeof theirs.text === "string" ? theirs.text : null; | ||
| if (room !== null) { | ||
| const res = merge3(saved, room, current()); | ||
| if (res.ok && applyText(res.text)) { |
There was a problem hiding this comment.
[P1] 서버가 병합 결과의 JSON 유효성 실패로 409를 반환해도 여기서는 텍스트 병합만 성공하면 결과를 적용하고 새 room 기준으로 다시 전송합니다. 예를 들어 [와 ] 사이에 각각 1과 2를 삽입한 두 유효한 JSON 배열은 쉼표 없는 [\n1\n2\n]로 합쳐지고, 재전송은 최신 base에 대한 직접 쓰기라 서버의 병합 유효성 검사를 통과하여 원본을 손상시킵니다. .json/.jsonl 결과를 적용하기 전에 서버와 동일하게 검증하고 실패 시 충돌 복사본으로 보존해 주세요. solo 재기반 및 늦은 join 경로에도 같은 검사가 필요합니다.
There was a problem hiding this comment.
Fixed in 8942b1b. Added validMergedText and merge3ForPath in src/lib/merge3.ts (matching Go's .json and .jsonl validation, while leaving one-sided edits unchecked so in-progress JSON typing is unaffected) and routed all 8 client merge/rebase sites in src/lib/sharedfile.ts through mergeForPath. Invalid combined JSON/JSONL merges on staging 409, solo rebaseOnHead, late join(), and external merge() now park a conflict copy or report "blocked" instead of rebasing and overwriting the file.
Verified with 59/59 node --test src/lib/sharedfile_restore.test.ts cases (covering staging 409, solo 409, late join(), and .jsonl validation) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- Done 저장이 지연되는 동안 축소 확인창이 열려도 타임아웃이 편집기를 닫아 확인과 편집 내용을 잃을 수 있습니다.
- 이전 지적의 클라이언트 JSON/JSONL 병합 검증, 빈 버퍼 전송 및 충돌 복사본 create-only 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| try { | ||
| okToLeave = await Promise.race([ | ||
| editFlushRef.current?.() ?? Promise.resolve(true), | ||
| new Promise<boolean>((r) => setTimeout(() => r(true), 1_500)), |
There was a problem hiding this comment.
[P1] 저장 요청이 1.5초 이상 걸리는 동안 축소 확인창이 열려도 이 타임아웃은 무조건 true를 반환하여 Done이 편집기를 닫습니다. 예를 들어 라이브 문서 내용을 대폭 지우고 Done을 누른 뒤 요청이 지연되면 700ms의 watchShrink가 확인창을 열지만, 1.5초에 편집기가 파괴되면서 질문이 철회되고 삭제도 저장되지 않습니다. 타임아웃 후에도 현재 askingShrink()를 별도로 확인해 질문이 열려 있으면 이탈을 막고, 지연 응답에서 질문이 열리는 경합도 처리해 주세요.
There was a problem hiding this comment.
Fixed in a94090b:
saveNow()insrc/lib/sharedfile.tsnow checkssharpShrink(byteLength(saved), byteLength(current()))synchronously before sending any request whenever this tab has unsent edits, opening the shrink dialog immediately without waiting on the network.FileView.tsxowns the boundedDonewait (1.5s, or 5s whendata.text === "" && !!data.shaso a hub-detected truncated-read shrink has room to answer) and checks!f.askingShrink()after the wait settles rather than resolvingtruefrom a timer inBrowser.tsx.
Verified with 64/64 node --test src/lib/sharedfile_restore.test.ts cases (including hung-network sharp shrinks across live, offline, staging, and solo modes plus slow server 422 responses) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- Done 대기 시간이 끝난 뒤 서버만 감지할 수 있는 축소 거절이 도착하면 확인 없이 편집기가 닫히고 미저장 편집이 유실될 수 있습니다. 이전 리뷰의 지연 응답 경합이 완전히 해결되지 않았습니다.
- 빈 버퍼 전송, bfcache 체크포인트 정산, JSON/JSONL 병합 검증 및 충돌 복사본 create-only 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| // Promise constructor, not withResolvers: the app targets ES2022. | ||
| let timer: ReturnType<typeof setTimeout> | undefined; | ||
| const waited = new Promise<void>((r) => { | ||
| timer = setTimeout(r, onlyHubSeesShrink ? 5_000 : 1_500); |
There was a problem hiding this comment.
[P1] 서버만 감지하는 축소는 5초 뒤에도 여전히 422를 반환할 수 있습니다. 예를 들어 불완전하게 읽힌 빈 seed에서 편집 후 Done을 누르고 응답이 5초 넘게 지연되면 타이머가 먼저 이탈을 허용합니다. 이후 422는 이미 파괴된 편집기에 도착해 확인창을 열지 못하고 변경도 저장되지 않습니다. 고정 대기 시간을 늘리는 대신 이 경우 결과가 확정될 때까지 이탈을 막거나, 늦은 422에서도 편집 버퍼와 확인 절차가 살아남도록 처리해 주세요.
There was a problem hiding this comment.
Fixed in 87c6406. Replaced the fixed 5,000 ms timer with mayServerRefuseShrink() on SharedFile: whenever only the server can detect a shrink (an empty saved === "" paired with a non-empty base SHA, or a solo/noRoomHttp conditional PUT where the server's file may have grown), FileView.tsx awaits saveNow() until it settles before allowing Done to leave, while keeping the 1,500 ms cap for ordinary saves where local sharpShrink already ran synchronously.
Verified with 65/65 node --test src/lib/sharedfile_restore.test.ts cases (including a 10,000 ms delayed server 422 test and mayServerRefuseShrink coverage across all modes) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 이전 Done/축소 확인 경합은 빈 seed 이외의 라이브 룸에서도 재현되어 미해결입니다.
- 빈 버퍼 종료 전송, bfcache 정산, JSON 병합 검증 및 충돌 복사본의 create-only 경로를 확인했습니다.
- 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.
| mayServerRefuseShrink: () => { | ||
| if (asking || gone || confirmShrinkOnce || !opts.onShrinkRefused) return false; | ||
| if (!base || base === EMPTY_SHA256) return false; | ||
| if (hubHoldsIt) return saved === "" && (localDirtyInRoom || pending > 0); |
There was a problem hiding this comment.
[P1] 라이브 룸에서 saved가 비어 있지 않더라도 서버만 축소를 감지할 수 있습니다. 예를 들어 다른 편집자가 큰 내용을 추가해 허브가 스냅샷을 저장했지만 이 탭의 파일 변경 알림은 아직 도착하지 않은 상태에서, 사용자가 그 내용을 삭제하고 기존 짧은 텍스트에 단어를 추가하면 saved 대비로는 축소가 아니지만 서버 파일 대비로는 급격한 축소입니다. mustSettle이 false이므로 Done은 1.5초 뒤 편집기를 닫고, 늦게 도착한 422는 파괴된 편집기에서 확인할 수 없어 저장되지 않습니다. 룸의 저장된 최신 크기를 확실히 알 수 없는 경우에도 결과가 확정될 때까지 이탈을 막거나 늦은 422를 처리할 버퍼와 확인 절차를 유지해 주세요.
There was a problem hiding this comment.
Fixed in 9fe7bba. Removed mayServerRefuseShrink and the fixed 1,500 ms timer completely so FileView.tsx awaits f.saveNow() until it settles in every mode (including a live room where a peer's snapshot grew the server file before SSE notified this tab) and checks !f.askingShrink(), with leavingFlushRef guarding duplicate clicks on the active editor's flush closure.
Verified with 65/65 node --test src/lib/sharedfile_restore.test.ts cases (including a 10,000 ms delayed 422 shrink refusal on a non-empty live room) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- Done 저장 중 추가 편집은 저장 결과를 기다리지 않고 이탈해 늦은 축소 거절과 편집 유실이 다시 발생할 수 있습니다.
- 저장 실패도 성공처럼 이탈해 재시도가 취소되고 미저장 버퍼가 파괴될 수 있습니다.
- 기존 고정 타임아웃 제거와 빈 버퍼 종료 전송, JSON 병합 검증 및 충돌 복사본 create-only 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 패키지 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| if (out.update) collab.applyRemoteUpdate(out.update); | ||
| adopt(out.text, out.sha); | ||
| // Typing that landed while this was out is not in it. | ||
| roomHandedOver(sentRoomSeq); |
There was a problem hiding this comment.
[P1] Done이 이 요청을 기다리는 동안에도 편집기는 활성 상태입니다. 요청 이후 사용자가 추가 편집하면 roomHandedOver(sentRoomSeq)가 dirty 상태를 유지하지만 이 Promise는 그대로 완료되어 Done이 편집기를 닫습니다. 특히 추가 편집이 축소라면 teardown의 별도 요청에서 늦게 422가 도착해도 이미 파괴된 편집기에서 확인할 수 없습니다. 저장 중 편집을 막거나 새 sequence까지 반복 체크포인트하고 각 결과/축소 확인이 정산된 뒤에만 Done이 이탈하게 해 주세요.
There was a problem hiding this comment.
Fixed in a14f2a4. saveNow() now loops while owesSave() remains true (running askIfShrunk() before each pass), so edits or shrinks typed while an earlier pass is on the wire are checkpointed and shrink-checked before saveNow() resolves.
Verified with 72/72 node --test src/lib/sharedfile_restore.test.ts cases (including concurrent typing and concurrent shrinks during in-flight saveNow() across live and solo modes) and ./check-dist.sh.
| } catch { | ||
| // The editor's own teardown still sends what it holds. | ||
| } | ||
| if (f.askingShrink()) return false; |
There was a problem hiding this comment.
[P1] saveNow()는 네트워크 오류나 403/503을 내부에서 처리하고 정상 완료할 수 있으므로 축소 확인만 검사하면 저장되지 않은 상태에서도 Done이 이탈합니다. 예를 들어 staging 저장이 503이면 재시도가 예약되지만 unmount의 destroy()가 이를 취소하고 종료 요청 한 번만 시도하므로 장애가 지속되면 유일한 편집 버퍼가 사라집니다. 저장 성공/실패를 명시적으로 반환하고 미저장 또는 보존 실패 시 편집기를 유지하여 재시도할 수 있게 해 주세요.
There was a problem hiding this comment.
Fixed in a14f2a4. saveNow() now returns Promise<boolean> (false whenever a shrink confirmation opens or a pass fails to advance due to 503/403/network error or an unparked conflict), and FileView.tsx keeps the editor and its retry timers open whenever !saved || f.askingShrink().
Verified with 72/72 node --test src/lib/sharedfile_restore.test.ts cases (covering 503 failures and subsequent recovery across live, offline, staging, solo, and conflict-park paths) and ./check-dist.sh.
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 비신뢰 iframe의 DOM 쓰기 차단이 다른 JavaScript realm의 네이티브 메서드 및 반사 속성 setter로 우회될 수 있어 이전 보안 차단 문제가 완전히 해소되지 않았습니다.
- 프레임 채널 분리, 범위 내용 대조 및 bfcache worker 재무장 경로를 확인했습니다.
- 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| }; | ||
|
|
||
| // The open element and everything in it. | ||
| setters(Element.prototype, ["innerHTML", "outerHTML"], (s) => hostWrite(s, [])); |
There was a problem hiding this comment.
[P1] 이 래퍼는 현재 realm의 프로토타입만 보호합니다. 비신뢰 HTML이 about:blank 자식 iframe의 Element.prototype.innerHTML 원본 setter를 얻어 열린 편집 요소에 call하면 이 검사를 거치지 않고 DOM을 바꿀 수 있습니다. HTMLAnchorElement.href 같은 반사 속성 setter도 별도로 가로채지 않습니다. 특히 실제 붙여넣기 중에는 allowRichPaste가 켜져 텍스트 예산과 일치하는 변경에 임의의 링크 마크가 섞일 수 있으므로 사용자 입력에 편승한 내용 변경을 배제하지 못합니다. DOM 공유 realm의 프로토타입 패치에 의존하지 않는 격리된 편집 경계에서 입력을 수집하고, 다른 차단 시도를 섞지 않은 교차 realm setter/링크 변조와 실제 붙여넣기 회귀 테스트를 추가해 주세요.
There was a problem hiding this comment.
Fixed in b2098d7:
-
mount(el)(src/inline-edit.ts) now isolates ProseMirror's active editing DOM inside a closed Shadow Root (rawAttachShadow.call(shadowHost, { mode: "closed" }), captured at$t = 0$ before any page script runs), cloning inert page stylesheets and built-in ancestor selector context (safeMirrorTag, refusing hyphenated custom elements) into the closed shadow tree and writing the serialized inner HTML back ontoel's light DOM onunmount(). - Because
shadowRootisnullacross all realms and events retarget outside the closed boundary, pre-saved light-DOM references (HTMLAnchorElement.prototype.hrefsetter, even during real paste whenallowRichPasteis active!), event-target queries, and cross-realmabout:blankElement.prototype.innerHTMLsetters cannot reach ProseMirror's live nodes; detachingelorshadowHosttriggersclobberFromScript()(bd-edit:clobbered) without saving. - Added all 3 isolated, unmixed Chromium Playwright E2E regression tests in
e2e/inline-edit.spec.ts(24/24E2E tests pass):- Pure reflected
HTMLAnchorElement.prototype.hrefsetter during real typing, - Pure cross-realm
about:blankElement.prototype.innerHTMLsetter during real typing, and - Real user paste (
ControlOrMeta+v) while hostilepaste/beforeinput/inputlisteners attempt linkhrefhijacking and clipboard markup injection.
- Pure reflected
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 닫힌 shadow root의 내부 노드가 페이지가 교체한 DOM 메서드를 통해 노출되어 이전 보안 차단 문제가 여전히 남습니다.
- iframe 채널 분리와 bfcache 재무장 경로를 확인했습니다. 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.
| noticeable way a click-to-edit surface can feel broken. */ | ||
| function caretAt(v: EditorView, x: number, y: number) { | ||
| const at = v.posAtCoords({ left: x, top: y }); | ||
| const rect = v.dom.getBoundingClientRect(); |
There was a problem hiding this comment.
[P1] 비신뢰 페이지가 편집 시작 전에 Element.prototype.getBoundingClientRect를 교체하면 실제 클릭으로 caretAt이 호출될 때 래퍼의 this로 닫힌 shadow root 안의 v.dom을 획득합니다. this.getRootNode() 및 하위 노드에 접근할 수 있으므로 다른 realm의 네이티브 setter나 href setter로 편집 중인 DOM을 변조할 수 있고, 특히 실제 붙여넣기 중에는 변경이 사용자 입력에 편승해 저장될 수 있습니다. 기존 cross-realm 차단 문제가 해소되지 않았습니다. 비신뢰 코드와 편집기를 별도 실행 경계로 격리하고, 프로토타입 메서드 교체로 내부 노드를 탈취한 뒤 실제 붙여넣기 중 링크를 변조하는 회귀 테스트를 추가해 주세요.
There was a problem hiding this comment.
Fixed in 10a5961:
-
caretAtnow calls nativeElement.prototype.getBoundingClientRectcaptured at$t = 0$ , andinstallGuards()freezes all DOM/WebIDL,Event,Range,Selection, and geometry prototypes (proto instanceof EventTarget || proto instanceof Event || extraDOMProtos.has(proto)) before any page script executes so page scripts cannot replaceElement.prototype.getBoundingClientRect,getClientRects,HTMLElement.prototype.focus, orShadowRoot.prototype.*to stealv.domorthis.getRootNode(). -
parseMarkup/parseInner/serializeInnernow parse HTML inside a fresh inert<template>rather than walking live page-owned DOM nodes. - Replaced the blanket
allowRichPasteboolean withallowedPasteMarks: Set<string>extracted strictly from the trustedClipboardEvent/InputEventtext/htmlpayload, so unchanged spans always enforcePMMark.sameSeteven during a paste and pasted text may only carry marks present in the clipboard'stext/html(or cursor/adjacent marks). - Added the prototype-method replacement + shadow-node theft + real paste link-tampering E2E regression test in
e2e/inline-edit.spec.ts(stolen === 0,25/25Playwright E2E tests pass).
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 비신뢰 페이지가 변경 가능한 JavaScript 내장 프로토타입을 통해 종료 패치를 위조할 수 있어 이전 보안 차단 문제가 남아 있습니다.
- 닫힌 shadow root 보호, 범위 검증 및 bfcache 재무장 경로를 확인했습니다.
- 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| frame, decides whether and how it is saved. */ | ||
| function exitUnacked() { | ||
| if (!exitPort) return; | ||
| const patches = unackedExitPatches(editedSpans.values()); |
There was a problem hiding this comment.
[P1] Map.prototype은 동결되지 않아 비신뢰 페이지가 values를 교체하면 여기서 호출될 때 비공개 editedSpans 맵을 this로 얻고 각 항목의 html과 acked를 바꿀 수 있습니다. 사용자가 정상 편집 후 탭을 닫으면 위조된 범위 내용이 봉인된 포트로 worker에 전달되고, 유효한 범위와 script 없는 HTML이므로 세션 권한으로 저장됩니다. shadow root 및 신뢰 이벤트 검사를 우회하는 경로입니다. 비신뢰 코드와 편집 상태를 별도 실행 경계로 격리하고, 내장 프로토타입 교체로 종료 패치를 변조하는 회귀 테스트를 추가해 주세요.
There was a problem hiding this comment.
Fixed in 0a6851e:
- Moved
editedSpans,ackEditedSpan, andunackedExitPatchescompletely out ofsrc/inline-edit.tsintosrc/lib/editexit.worker.ts's isolatedWorkerGlobalScoperealm:inline-edit.tsstreams{ type: "bd-edit:span", seq, start, end, html }on each edit and{ type: "bd-edit:exit" }(with no payload) on unload, whileVisualEdit.tsxsends{ type: "ack", seq }directly toeditexit.worker.ts(retaining early acks inackedSeqssoackandbd-edit:spancommute across channels). - Uncurried all internal
WeakMap/Map/Set/MessagePortoperations ininline-edit.tsat$t = 0$ viaFunction.prototype.bind.bind(Function.prototype.call), so page scripts replacingMap.prototype.values/set,Array.prototype.sort/map,JSON.stringify, orFunction.prototype.callcannot observe or tamper with exit patches. - Added the
Map/Array/JSONprototype-replacement exit-patch regression test ine2e/inline-edit.spec.ts(26/26Playwright E2E tests pass).
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 비신뢰 페이지가 범위 검증 이후 편집 시작 전에 요소 내용을 바꾸면 사용자 권한으로 위조된 내용이 저장되는 보안 차단 문제가 남아 있습니다.
- 이전 Map 기반 종료 패치 변조는 worker 분리로 해소되었으나, 최초 범위 검증과 편집 시작 사이의 내용 무결성은 보장되지 않습니다.
- 클린 체크아웃에 패키지 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
Unanchored Findings (outside changed diff lines)
internal/webapp/frontend/src/inline-edit.ts:842: [P1]initDOM에서 기록한initialHtml은 부모가 한 번만 검증하지만, 비신뢰 페이지 스크립트는 그 이후host가 아직 없을 때 해당 요소의innerHTML을 자유롭게 바꿀 수 있습니다. 사용자가 그 요소를 클릭하면 여기서 변조된 현재 DOM을 편집기 초기 문서로 읽고, 정상적으로 한 글자만 입력해도flush()가 변조 내용 전체를 유효한 범위의 패치로 전송하여 사용자 세션 권한으로 저장합니다. 편집 시작 시 신뢰된 원본과 현재 내용을 다시 대조하고 불일치하면 편집을 거부하거나, 검증된 원본을 별도 신뢰 경계에서 편집기에 공급해 주세요. 초기화 후 클릭 전 DOM 변조 회귀 테스트도 필요합니다.
|
Re: unanchored finding on Fixed in 3af174b:
|
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- 비신뢰 페이지가 변경 가능한 배열 프로토타입을 통해 편집기의 내부 마크를 탈취·변조하여 사용자 권한으로 저장할 수 있습니다.
- 이전 지적의 클릭 전 DOM 변조 검증과 종료 worker 분리 경로를 확인했으나, 공유 JavaScript realm의 무결성 문제는 남아 있습니다.
- 클린 체크아웃에서 로컬 패키지 테스트는 실행하지 않았습니다.
| doc.descendants((node) => { | ||
| if (!node.isText || !node.text) return; | ||
| const t = node.text.replace(/\u00a0/g, " "); | ||
| for (let i = 0; i < t.length; i++) out.push({ ch: t[i], marks: node.marks }); |
There was a problem hiding this comment.
[P1] 비신뢰 페이지가 편집 전에 Array.prototype.push를 교체하면 실제 입력 중 이 호출의 인자로 전달되는 node.marks에 접근할 수 있습니다. 예를 들어 기존 링크의 rawInline 마크에 있는 marks[0].attrs.attrs.href를 바꾸면 이전/다음 ProseMirror 문서가 공유하는 마크 자체가 변조되어 비교와 입력 예산 검사를 통과하고, 정상 타이핑에 편승해 위조된 링크가 저장됩니다. 닫힌 shadow root와 worker 분리로도 보호되지 않습니다. 비신뢰 코드와 편집 상태를 별도 실행 경계로 분리하고, 최소한 변경 가능한 내장 메서드에 내부 마크 참조를 넘기지 않도록 하며 이 프로토타입 교체 후 실제 타이핑하는 회귀 테스트를 추가해 주세요.
There was a problem hiding this comment.
Fixed in 4d98490:
RawInline.parseHTML().getAttrsnow storesattrson aObject.freeze(Object.create(null))record, somark.attrs.attrs(href) cannot be mutated in place even if a reference were obtained.charsWithMarksand the mark-diff loop indispatchTransactionno longer invoke.push,.slice,.map,.join,.includes, or.everyvia mutable prototype lookups (using indexed assignment onto frozen null-prototypeCharUnitrecords and uncurriedstrReplace/strIncludes).installGuards()locks all existing own methods/accessors on JS built-in intrinsics (Array.prototype,Map.prototype,String.prototype,RegExp.prototype,Function.prototype,JSON,Reflect, etc.) aswritable: false, configurable: false(leaving prototypes extensible for new polyfill methods while sealingObject.prototypewith SES-style safe-override accessors).- Added the
Array.prototype.push/map/slice+Object.prototypemark-tampering regression test during real typing ine2e/inline-edit.spec.ts(28/28Playwright E2E tests pass).
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- bfcache 진입 시 종료 저장이 실패하면 미전달 편집을 이미 저장된 것으로 표시해, 복귀 후 다음 종료에서도 편집이 유실될 수 있습니다.
- 기존 클릭 전 DOM 무결성 검사, 내장 프로토타입 잠금 및 bfcache 채널 재무장 경로와 협업 HTTP 쓰기 권한 계약을 확인했습니다.
- 클린 체크아웃에 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| childPort?.close(); | ||
| childPort = null; | ||
| const patches = unackedExitPatches(editedSpans.values()); | ||
| for (const s of editedSpans.values()) { |
There was a problem hiding this comment.
[P1] bfcache 진입 시 부모가 아직 받지 못한 편집을 여기서 네트워크 요청 전에 승인 처리합니다. 오프라인이나 503 등으로 아래 fetch가 실패해도 rearm은 이 상태를 유지하므로, 복귀 후 다른 영역을 편집하고 다시 닫으면 첫 편집이 ackedHtml 조상에만 포함되어 실제 문서에서 삭제된 것으로 병합되거나 재전송 대상에서 빠집니다. 요청의 성공 및 실제 반영을 확인한 뒤에만 해당 스냅샷을 승인하고, 실패·모호한 결과에서는 미승인 상태를 유지해 복귀 후 재시도/조회를 하도록 수정해 주세요. 첫 종료 저장 실패 → pageshow → 두 번째 편집 및 종료 회귀 테스트가 필요합니다.
There was a problem hiding this comment.
Fixed in 58f546a:
sendUnacked(src/lib/editexit.worker.ts) no longer markseditedSpansacknowledged beforefetchcompletes:confirmSeqs(sentSeqs)runs only after a confirmed200 OK(out.ok === true).- On
5xx(including503) or network/ambiguous failures, spans remain unacknowledged (acked: false),recordAmbiguousretainspriorSentTexts(prior_sentonycollab/sync), andreconcileAfterRearm()onpageshowprobes{ peek: true }to advanceackedHtml/docTextwhen the live room already holds the attempt while keepings.acked = falseand schedulingscheduleRearmRetry()until a durable sync succeeds (withbuildExitSaveRequeststill sending when reverting back tosavedTextover an outstanding ambiguous room state). - Added the failed-first-exit (
503) ->pageshow-> second undelivered edit -> tab-close E2E regression test ine2e/inline-edit.spec.ts(29/29Playwright E2E tests pass).
… and reconcile on rearm
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: not-ready
- bfcache 복귀 후 종료 저장 재시도와 새 편집 승인 응답이 역순으로 도착하면 편집 조상이 뒤로 이동하여 후속 종료 저장에서 내용이 중복될 수 있습니다.
- 실패한 종료 요청을 성공 전에 승인하지 않는 수정과 재무장·재시도 경로를 확인했습니다.
- 클린 체크아웃에 의존성과 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
| if (!exited && !disarmed && state === curState) reconcileAfterRearm(); | ||
| return; | ||
| } | ||
| confirmSeqs(sentSeqs); |
There was a problem hiding this comment.
[P1] 복귀 후 이전 종료 편집의 재시도가 진행 중일 때 같은 요소를 다시 편집하면 앱의 새 ack가 먼저 ackedHtml을 최신 내용으로 전진시킬 수 있습니다. 이후 늦게 도착한 이 요청의 성공 응답이 이전 sentSeqs를 다시 승인하면서 ackEditedSpan이 ackedHtml을 이전 내용으로 되돌립니다. 다음 미전달 편집의 종료 저장은 이미 앱 문서에 반영된 새 편집을 조상에 없는 삽입으로 다시 병합해 중복할 수 있습니다. 범위별로 마지막 승인 seq를 기록하고 오래된 승인이 조상을 덮어쓰지 않게 하며, 재시도 응답보다 새 ack가 먼저 도착한 뒤 같은 요소를 다시 편집·종료하는 회귀 테스트를 추가해 주세요.
There was a problem hiding this comment.
Fixed in d85c0c7:
EditedSpan(src/lib/editbeacon.ts) now tracks monotonicackedSeq, andackEditedSpan(as well aspeekandbd-edit:spanupdates ineditexit.worker.ts) advancesackedHtmlonly whens.ackedSeq === undefined || seq > s.ackedSeq, so a late exit-save response confirming an olderseqnever rollsackedHtmlbackward behind a newer appack(andworkerSavedonly updates whilestate.savedText === fromText).- Added both unit assertions in
sharedfile_restore.test.tsand the out-of-order late exit-save response + same-element edit + close E2E regression test ine2e/inline-edit.spec.ts(30/30Playwright E2E tests pass).
runbear-bot
left a comment
There was a problem hiding this comment.
Bobb's bot(Totoro) Review
Conclusion: ready-with-notes
- 이전 차단 사항인 종료 저장 실패 후 미승인 유지와 역순 승인 시 범위별
ackedSeq단조 증가 처리를 확인했습니다. - 협업 HTTP 동기화의 경로 쓰기 권한 검사와 syncer의 승자 콘텐츠 기반 병합·중복 생략 계약을 확인했습니다.
- 클린 체크아웃에 패키지 의존성과 실행 도구가 없어 로컬 패키지 테스트는 실행하지 않았습니다.
TL;DR
.bdrive-conflict-*copies when saving or leaving edit mode, and closing a tab sends pending edits withkeepalivewhen the encoded HTTP request body is at most 60,000 bytes.write/edit, live rooms, andbdrive sync..bdrive-conflict-*copy, a tab-close request body over 60,000 bytes goes out withoutkeepaliveand the browser may cancel it, and v0.18.9 hub processes cannot read the newydoc/head/<path>records, so hubs sharing a storage root must upgrade together.What & why
Co-editing conflicts and silent rollbacks came from three surfaces disagreeing on who owned the document and how concurrent edits merged:
internal/webapp/ycollab.go,collab_relay.go,cmd/bdrive/desktop.go):ydoc/head/<path>now stores{sha, win}, wherewinis the monotonicwinKeyof the journal op that produced the stored state. Older folds cannot move the head backwards, andknows()compares states through a scratch merge so histories with deletions match accurately. Empty rooms remain warm for 2 minutes (collabRoomIdleTimeout), Redis streams retain 30 minutes of updates with state republishing on snapshot retries,moveDocLivereconciles outside writes as CRDT item deltas from an atomic snapshot, andPOST /api/p/{project}/ycollab/sync(also proxied bybdrive desktop) checkpoints browser edits into the room with an 8-second cross-instance durability wait (snapshotMaxlowered from 10s to 6s).internal/textmerge/merge.go,frontend/src/lib/merge3.ts,upload.go,mcp.go,internal/syncer/): Both Go and TypeScript now diff with Myers O(ND), merge independent hunks and non-overlapping intra-line word changes, and order same-point insertions deterministically while preserving.json/.jsonlvalidity. ConditionalPUT /api/p/{project}/upload/contentand MCPwrite/editmerge staleIf-Matchbases on the server and recordOp.Base, whileinternal/syncermerges against the winning op and skips writing a duplicate op when the merged digest already matches the winner.collab.ts,sharedfile.ts,editbeacon.ts,editexit.worker.ts,inline-edit.ts,Editor.tsx,VisualEdit.tsx,FileView.tsx,Browser.tsx,htmledit.go): Replaced the 8-secondCollabDoc.stop()cutoff with a 2.5-secondonStalledstaging buffer (stageDocinVisualEdit) that checkpoints overycollab/sync, peeks after ambiguous network failures, and splices minimal hunks on socket sync.save()and offline flushes are single-flight with sequence watermarks.Mod-scheckpoints immediately, andDoneawaitssaveNow()(nowPromise<boolean>) until every edit, including any typed during the save, is saved before leaving, and stays in the editor if the save fails or opens a shrink confirmation.pagehidesends unsent edits withkeepalivewhen the encoded HTTP request body is at most 60,000 bytes (KEEPALIVE_MAX_BYTES, below the browser's 64 KiB in-flightkeepalivelimit); a larger body goes out as a regularfetch, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down.pageshowresets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. TheVisualEditiframe stayssandbox="allow-scripts"and never receives a session, token or URL.stampEditablenow injects/inline-edit.jssynchronously before any page script, soinline-edit.tscaptures the nativeMessageChannel,MessagePortmethods andEvent.isTrustedfirst, uncurries theWeakMap/Map/Setbuiltins it uses, freezes the DOM, Event, Range, Selection and geometry prototypes, opens a privateMessageChannel, and sendsbd-edit:hellowith one port toVisualEditonce; all later editor traffic uses that sealed channel instead ofwindow.postMessage, edits require trusted user events, and pasted marks are whitelisted from the trusted clipboard'stext/htmlonly. The bootstrap tag also carriesdata-src-ranges;inline-edit.tsreads and strips itsdata-src-*attributes, locksdata-bd-src, binds each stamped element once in a privateWeakMap(rejecting duplicate or unstamped ranges), and refuses page-script writes to the open element (inEditorCalltaint tracking), reportingbd-edit:clobberedinstead of saving. The editor itself is mounted inside a closed shadow root (attachShadow({ mode: "closed" })on a<span data-bd-shadow>), so page scripts cannot reach its live nodes through reflected setters, saved light-DOM references or another realm's DOM setters, and the edited HTML is written back to the element's light DOM onunmount(); detaching the element or the shadow host also raisesbd-edit:clobbered.VisualEdit'sanchorRangeschecks each span's initial HTML against the source slice through an inert<template>(canonicalHTML) before anchoring it or arming the worker.VisualEditspawns a dedicated same-origin Web Worker (editexit.worker.ts), arms it with the rendered source, the anchored ranges and the live saved text, base sha and document text (kept current throughSharedFile'sonBaseChange), and hands the iframe one end of aMessageChannel(bd-edit:port). The iframe keeps no edited-span map:inline-edit.tsstreams each edit to the worker asbd-edit:span(seq,start,end,html),VisualEditpostsackwith theseqof each patch it applied straight to the worker, and on the iframe'sbeforeunload/pagehideit postsbd-edit:exit; all span and ack state lives in the worker's isolated realm. After a back/forward-cache restore,VisualEditre-arms the worker (rearm) with a freshbd-edit:port, so an edit left unacknowledged on a second close is saved too. The exit-worker save is best-effort and runs only once the worker has started and been armed. The worker splices only anchored, script-free spans onto the render, merges three ways with the current document, refuses an unconfirmed sharp shrink, and saves with the app's own cookie:POST ycollab/syncwithpark_on_conflicton a hub or desktop, orPUT upload/contenton the latestIf-Matchon a plain folder, so it also works after earlier auto-saves; a same-word clash parks a conflict copy.VisualEditsplices only changed spans inside an element, and post-savedroom snapshots advancesavedandbasewithout raising#peer-wrote.Upgrade notes
ydoc/head/<path>records older hubs wrote.ydoc/head/<path>as JSON ({sha, win}), which a v0.18.9 or earlier hub process cannot read. During a mixed-version rollout or a rollback, that older process skips the newest stored room state and falls back to the per-blob CRDT history (ydoc/<sha>) or, when none matches, to fresh file bytes. Multi-instance self-hosted operators should upgrade every hub process sharing a storage root together instead of running v0.18.9 and v0.18.10 side by side.Architecture changes
architecture/overview.mdThe
internal/textmergenode now describes the Myers multi-hunk diff3 merge with intra-line token merge and its four exports, and the hub's edge to it covers room reconciliation, conditionalupload/content, and MCPwrite/editinstead of only an outside write under a room.flowchart LR eng["internal/syncer Session.Cycle"] srv["internal/webapp Server"] tm_old["❌ <s>internal/textmerge: line-level three-way merge, non-overlapping regions only</s>"] tm["✅ internal/textmerge: Myers multi-hunk diff3 merge + intra-line token merge<br/>Merge, DiffHunks, RetainsChanges, IsText"] eng -->|concurrent edits from two devices| tm srv -.->|"❌ <s>an outside write under a co-editing room</s>"| tm_old srv -->|"✅ co-editing room reconciliation, conditional upload/content, MCP write / edit on a stale sha"| tmarchitecture/cli-sync.mdtextmergegainsDiffHunks,RetainsChanges, andIsText;mergegainslatestPut, soconflictCopiesWithStatemerges the losing op against the winning op, skips the op when the result equals the winner's blob, and recordsOp.Baseon a real merge.flowchart LR Session["Session.conflictCopiesWithState"] merge["merge (merge.go)<br/>tryMerge, mergeText, commonAncestor"] latestPut["✅ latestPut(path, blob, lists): the op that won"] ff["✅ merged blob == winner blob: fast-forward, no op"] base["✅ merge op records Op.Base = winning blob"] textmerge["textmerge<br/>Merge"] tmnew["✅ DiffHunks, RetainsChanges, IsText"] Session -->|before a conflict copy| merge merge --> latestPut merge --> ff merge --> base merge -->|the line merge itself| textmerge textmerge --- tmnewarchitecture/webapp-server.mdServergainshandleYCollabSync,syncDurable/awaitDurable,mergeStaleUpload,moveDocLive, andparkStaleUpload/stepConflictCopywith new edges toydocsandtextmerge, plus a note on park-on-conflict (X-Bdrive-Park-On-Conflictonupload/content,park_on_conflictonycollab/sync,validMergedTextfor.json/.jsonl);ydocsgains theydoc/headroomHeadRec{sha, win}fence,collabRoomIdleTimeout(2m), andsnapshotMax(6s, was 10s);CollabConfiggains a 30-minute stream retention;mcpToolsnow merges a stale sha through the upload door;editViewnow injects/inline-edit.jssynchronously before any page script instead of appending it, withdata-src-rangesbeside the hash and length.flowchart LR Server["Server"] ydocs["ydocs (ygo)"] textmerge["textmerge"] CollabConfig["CollabConfig<br/>Redis<br/>✅ collabStreamRetention 30m, collabStreamMaxLen 32768"] mcpTools["mcpTools write / edit"] sync["✅ handleYCollabSync: POST {prefix}ycollab/sync<br/>syncDurable / awaitDurable, ycollabSyncDurableWait 8s<br/>park_on_conflict text checkpoints"] msu["✅ mergeStaleUpload + Op.Base on conditional upload/content"] park["✅ parkStaleUpload / stepConflictCopy: X-Bdrive-Park-On-Conflict<br/>validMergedText for .json / .jsonl"] head["✅ ydoc/head/<path> = roomHeadRec {sha, win}: winKey fence, DeleteSet-safe knows()"] live["✅ moveDocLive: CRDT item delta from one atomic snapshot"] timers["✅ collabRoomIdleTimeout 2m, snapshotMax 6s"] editView["editView (htmledit.go, ?edit=1)<br/>❌ <s>appends /inline-edit.js</s><br/>✅ injects /inline-edit.js synchronously before any page script<br/>✅ data-src-hash, data-src-len, data-src-ranges"] Server -->|"serveBlob ?edit=1"| editView Server --> park Server --> sync Server --> msu Server -->|"✅ ycollab/sync applies a client state"| ydocs Server -->|"✅ mergeStaleUpload (Merge, RetainsChanges)"| textmerge ydocs -->|"reconcile an outside write (Merge), ✅ splice as minimal hunks (DiffHunks)"| textmerge ydocs --> head ydocs --> live ydocs --> timers CollabConfig -->|AttachRelay| ydocs mcpTools -->|"✅ stale sha becomes the If-Match base (staleShaError)"| msu msu -->|"✅ unmergeable stale base, park requested"| parkarchitecture/webapp-frontend.mdlibgainsmerge3.ts,frameflush.ts(frameChannel: an in-order queue of iframe messages that drains withbd-edit:flush/bd-edit:flushedbeforeVisualEditsaves;saveLocked: Done's flush carrieslock: true, andbd-edit:unlockreopens the frame whensaveNow()returnsfalseor throws),editbeacon.ts(ackEditedSpan,unackedExitPatches,applyRenderPatches,buildExitSaveRequest) andeditexit.worker.ts(a dedicated same-origin Web Worker that holds all edited-span and ack state:bd-edit:spanandbd-edit:exitarrive over the iframe'sbd-edit:portMessagePort,ackcomes straight fromVisualEdit; it is re-armed with a fresh port after a back/forward-cache restore and saves through same-originPOST ycollab/syncorPUT upload/content), and newcollab.ts/sharedfile.tsmembers (onStalledstaging replaces the 8sstop()solo fallback, plussaveNow,askingShrink,seenRoomTexts, thepagehidekeepalive flush, and thepageshowreset of its exit-send guard);apigainssyncCollabandkeepalive;Browserwaits on FileView'sflushReffor Done;EditorbindsMod-sandVisualEditstages intostageDoc;inline-edit.tstalks toVisualEditonly over a sealedMessageChannelopened bybd-edit:hello, freezes the DOM prototypes it relies on, binds the server'sdata-src-rangesonce and refuses page-script writes to the open element (bd-edit:clobbered);VisualEditverifies each span against the source (canonicalHTML) before anchoring it.flowchart LR Browser["Browser<br/>✅ Done saves via editFlushRef (saveNow) before leaving; stays on failure or a shrink question"] components["components<br/>✅ Editor Mod-s + staging buffer<br/>✅ VisualEdit stageDoc + minimal splice + handle<br/>✅ VisualEdit anchorRanges: canonicalHTML check before anchor / arm<br/>✅ FileView flushRef"] frame["✅ lib/frameflush.ts<br/>frameChannel: FIFO message queue, drain()<br/>saveLocked: drain + lock, save, unlock unless saved"] inline["inline-edit.ts (iframe bundle, sandbox allow-scripts)<br/>✅ runs before page scripts, captures native MessageChannel / isTrusted<br/>✅ uncurries WeakMap / Map / Set, freezes DOM, Event, Range, Selection, geometry prototypes<br/>✅ binds data-src-ranges once (WeakMap), locks data-bd-src<br/>✅ refuses page-script writes to the open element (inEditorCall)<br/>✅ editor mounted in a closed shadow root (span data-bd-shadow)<br/>✅ pasted marks only from trusted clipboard text/html<br/>✅ answers bd-edit:flush with bd-edit:flushed<br/>✅ lock: true stops edits until bd-edit:unlock<br/>✅ numbers patches (seq), keeps no edited-span map"] beacon["✅ lib/editbeacon.ts<br/>ackEditedSpan, unackedExitPatches,<br/>applyRenderPatches, buildExitSaveRequest"] worker["✅ lib/editexit.worker.ts<br/>dedicated same-origin Worker: arm / ack / sync / rearm / disarm<br/>holds all edited-span and ack state"] hub["same-origin POST ycollab/sync (hub, desktop)<br/>or PUT upload/content with If-Match (plain folder)"] collab["lib/collab.ts CollabDoc<br/>❌ <s>stop = solo for good after 8s</s><br/>✅ onStalled (2.5s), encodeState, applySplices, applyRemoteUpdate"] merge3["✅ lib/merge3.ts<br/>merge3, merge3PreferRight, merge3ForPath, validMergedText, diffSplices, applySplices, retainsChanges"] shared["lib/sharedfile.ts<br/>✅ staging checkpoints + peek recovery<br/>✅ single-flight save, saveNow, askingShrink<br/>✅ pagehide keepalive flush (60,000 bytes), pageshow resets exit guard<br/>✅ seenRoomTexts"] api["api/http.ts<br/>✅ syncCollab, putText keepalive"] Browser -.->|"✅ Done awaits flushRef"| components components -->|openSharedFile| shared components -->|"✅ merge3PreferRight diffSplices (VisualEdit)"| merge3 components -->|"✅ saveLocked(frameChannel drain, saveNow, unlock) (VisualEdit)"| frame frame -.->|"✅ bd-edit:flush {lock} / bd-edit:flushed, bd-edit:unlock on a failed save"| inline inline -.->|"✅ bd-edit:hello once, with a sealed MessageChannel port"| components inline -.->|"✅ bd-edit:clobbered on a page-script write, nothing saved"| components components -->|"✅ ack { seq } per applied patch"| worker components -->|"✅ spawns + arms (render, allowedRanges, savedText / baseSha / docText via onBaseChange)"| worker components -.->|"✅ bd-edit:port (MessageChannel end), fresh one on bfcache pageshow"| inline components -->|"✅ rearm on bfcache pageshow"| worker inline -->|"✅ bd-edit:span { seq, start, end, html } on each edit, bd-edit:exit on beforeunload / pagehide"| worker worker --> beacon worker -->|"✅ app's own cookie, keepalive up to 60,000 bytes"| hub shared --> collab shared -->|"✅ merge3ForPath diffSplices retainsChanges"| merge3 shared -->|"✅ syncCollab putText keepalive"| apiChecklist
go build ./... && go vet ./... && go test ./...green (including-raceacross all non-webapp packages and./internal/webapp -run 'Collab|Concurrent|Stress|Events|Presence|Upload|Store', plusTestCollabEightPeersMeetingNoteExitChaoswith 8 concurrent editors across 2 hub instances: 726 edits, 0 conflicts)internal/syncer(merge_test.go,merge_contentproof_test.go)npm run buildre-committedinternal/webapp/static,./check-dist.shclean, 35/35node --test src/lib/sharedfile_restore.test.tsgreen, and 49/49 Playwright E2E editing/co-editing specs green (edit-url,concurrent-edit,solo-handoff,reconnect,meeting-editor,inline-edit,empty-save,zz-stress-edit)